﻿using System;
using System.IO;
using System.Net;

namespace UtilsExtensionsAndHelpers.Helpers.Implimentations
{
    /// <summary>
    /// Helpful methods for manipulating images. 
    /// </summary>
    public class ImageHelper : IImageHelper
    {
        private Action<String> _feedbackProvider;
        /// <summary>
        /// Get or set the action that provides feedback. 
        /// A message (string) will be passed in.
        /// IE. Log(message), Console.WriteLine(message)
        /// </summary>
        public Action<String> FeedbackProvider
        {
            get { return _feedbackProvider ?? Console.WriteLine; }
            set { _feedbackProvider = value; }
        }

        /// <summary>
        /// Gets a url from an image url and converts it to byte[]
        /// </summary>
        /// <param name="url">The url of the image.</param>
        /// <returns>byte[]  A collection of byte representing the image</returns>
        public byte[] ImageUrlToBytes(string url)
        {
            byte[] imageBytes = null;
            var webClient = new WebClient();
            try
            {
                imageBytes = webClient.DownloadData(url);
            }
            catch (Exception e)
            {
                FeedbackProvider(e.Message);
                throw;
            }
            finally
            {
                webClient.Dispose();
            }
            return imageBytes;
        }

        /// <summary>
        /// Gets a url from an image url and converts it to byte[]
        /// </summary>
        /// <param name="url">The url of the image.</param>
        /// <returns>byte[]  A collection of byte representing the image</returns>
        public byte[] LocalImageUrlToBytes(string path)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(path);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            using (FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {

                //Use BinaryReader to read file stream into byte array.
                BinaryReader br = new BinaryReader(fStream);

                //When you use BinaryReader, you need to 

                //supply number of bytes to read from file.
                //In this case we want to read entire file. 

                //So supplying total number of bytes.
                data = br.ReadBytes((int) numBytes);
                return data;
            }
        }
    }
}
